package cn.tenmg.flink.jobs.quickstart.utils;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.tenmg.flink.jobs.quickstart.exception.RequestResolveException;

/**
 * HTTP请求工具类
 * 
 * @author June wjzhao@aliyun.com
 *
 */
public class HttpUtils {

	public static String getRequestBody(HttpServletRequest req) {
		ServletInputStream is = null;
		try {
			is = req.getInputStream();
			StringBuilder sb = new StringBuilder();
			byte[] bytes = new byte[1024];
			while (is.read(bytes) != -1) {
				sb.append(new String(bytes, "UTF-8"));
			}
			return sb.toString();
		} catch (IOException e) {
			throw new RequestResolveException(e);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void response(HttpServletResponse resp, Object data) throws IOException {
		resp.setContentType("application/json;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");
		PrintWriter pw = resp.getWriter();
		pw.write(JSON.toJSONString(data));
		pw.flush();
		pw.close();
	}

}
